/*
 * Copyright (C) 2019 Chatopera Inc, <https://www.chatopera.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chatopera.cc.aspect;

import com.alibaba.fastjson.JSON;
import com.chatopera.cc.basic.Constants;
import com.chatopera.cc.basic.MainContext;
import com.chatopera.cc.basic.MainUtils;
import com.chatopera.cc.controller.Handler;
import com.chatopera.cc.model.RequestLog;
import com.chatopera.cc.model.User;
import com.chatopera.cc.util.Menu;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Enumeration;

/**
 * 请求日志，替代LogIntercreptorHandler
 */
@Aspect
@Component
public class RequestLogAspect {
    private final static Logger logger = LoggerFactory.getLogger(RequestLogAspect.class);

    /** 以 controller 包下定义的所有请求为切入点 */
    @Pointcut("execution(public * com.chatopera.cc.controller..*.*(..))")
    public void webLog() {}


    @Before("webLog()")
    public void logRequest(JoinPoint jp) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MethodSignature methodSign = (MethodSignature)jp.getSignature();
        Object handlerBean = jp.getTarget();
        RequestLog log = new RequestLog();
        log.setEndtime(new Date());
        RequestMapping obj = methodSign.getMethod().getAnnotation(RequestMapping.class);
        if (obj != null) {
            log.setName(obj.name());
        }
//        log.setMethodname(handlerMethod.toString());
        log.setMethodname(methodSign.getName());
        log.setIp(request.getRemoteAddr());
        if (handlerBean != null) {
            log.setClassname(handlerBean.getClass().toString());
            if (handlerBean instanceof Handler && ((Handler) handlerBean).getStarttime() != 0) {
                log.setQuerytime(System.currentTimeMillis() - ((Handler) handlerBean).getStarttime());
            }
        }
        log.setUrl(request.getRequestURI());

        log.setHostname(request.getRemoteHost());
        log.setEndtime(new Date());
        log.setType(MainContext.LogType.REQUEST.toString());
        User user = (User) request.getSession(true).getAttribute(Constants.USER_SESSION_NAME);
        if (user != null) {
            log.setUserid(user.getId());
            log.setUsername(user.getUsername());
            log.setUsermail(user.getEmail());
            log.setOrgi(user.getOrgi());
        }
        StringBuffer str = new StringBuffer();
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String paraName = names.nextElement();
            if (paraName.indexOf("password") >= 0) {
                str.append(paraName).append("=").append(MainUtils.encryption(request.getParameter(paraName))).append(",");
            } else {
                str.append(paraName).append("=").append(request.getParameter(paraName)).append(",");
            }
        }

//        Menu menu = handlerMethod.getMethod().getAnnotation(Menu.class);
        Menu menu = methodSign.getMethod().getAnnotation(Menu.class);
        if (menu != null) {
            log.setFuntype(menu.type());
            log.setFundesc(menu.subtype());
            log.setName(menu.name());
        }

        log.setParameters(str.toString());
        logger.info(JSON.toJSONString(log));
    }
}
